package com.itgan.userbackendmanagement.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itgan.userbackendmanagement.common.enumeration.ErrorCodeEnum;
import com.itgan.userbackendmanagement.constant.UserConstant;
import com.itgan.userbackendmanagement.context.BaseContext;
import com.itgan.userbackendmanagement.exception.BusinessException;
import com.itgan.userbackendmanagement.mapper.UserMapper;
import com.itgan.userbackendmanagement.pojo.dto.LoginDTO;
import com.itgan.userbackendmanagement.pojo.dto.RegisterDTO;
import com.itgan.userbackendmanagement.pojo.entity.User;
import com.itgan.userbackendmanagement.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.itgan.userbackendmanagement.constant.MessageConstant.*;
import static com.itgan.userbackendmanagement.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 24057
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2024-08-28 20:44:18
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Resource
    private UserMapper userMapper;

    /**
     * 登录
     * @param loginDTO
     */

    public User doLogin(LoginDTO loginDTO, HttpServletRequest request) {
        User user = new User();
        BeanUtils.copyProperties(loginDTO,user);

        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(user.getUserAccount());
        if (matcher.find()) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,OPERATION_EXCEPTION);
        }
        if (user.getUserAccount().length() < 4) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,ACCOUNT_LENGTH_DOES_NOT_MATCH);
        }
        if (user.getPassword().length() < 6) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,PASSWORD_LENGTH_DOES_NOT_MATCH);
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_account",user.getUserAccount());
        String encryptPassword = DigestUtils.md5DigestAsHex((UserConstant.SALT + user.getPassword()).getBytes(StandardCharsets.UTF_8));
        userQueryWrapper.eq("password",encryptPassword);
        User user1 = userMapper.selectOne(userQueryWrapper);
        if (user1==null){
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,USER_NOT_LOGIN);
        }
        User safetyUser = getSafetyUser(user1);

        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        BaseContext.setCurrentId(safetyUser.getId());

        return safetyUser;

    }

    /**
     * 注册
     * @param registerDTO
     */

    public int register(RegisterDTO registerDTO) {
        if (registerDTO.getUserAccount().length()<4){
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,ACCOUNT_LENGTH_DOES_NOT_MATCH);
        }
        if (registerDTO.getPassword().length()<6){
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,PASSWORD_LENGTH_DOES_NOT_MATCH);
        }
        String valiedpawd = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(valiedpawd).matcher(registerDTO.getUserAccount());
        if (matcher.find()){
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,SPECIAL_SYMBOL_ACCOUNT_EXCEPTION);
        }
        if (!registerDTO.getPassword().equals(registerDTO.getCheckPassword())){
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,INCONSISTENT_PASSWORDS);
        }
        User user = new User();
        BeanUtils.copyProperties(registerDTO,user);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", user.getUserAccount());
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,ALREADY_EXISTS);
        }

        String encryptPassword = DigestUtils.md5DigestAsHex((UserConstant.SALT + user.getPassword()).getBytes(StandardCharsets.UTF_8));
        user.setUserAccount(user.getUserAccount());
        user.setPassword(encryptPassword);
        int result = userMapper.insert(user);
        return result;

    }

    /**
     *
     */
    @Override
    public void addUser() {

    }

    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setPassword("****");
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setIsDelete(originUser.getUserRole());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUpdateTime(originUser.getUpdateTime());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setUserState(originUser.getUserState());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }




}




